package com.yeskery.nut.core;

import java.util.function.Consumer;

/**
 * 响应发射器
 * @author YESKERY
 * 2024/7/9
 */
public class ResponseBodyEmitter implements ResponseEmitter {

    /** 超时时间 */
    private long timeout = 60L;

    /** 超时回调函数 */
    private Runnable onTimeout;

    /** 完成回调函数 */
    private Runnable onCompletion;

    /** 错误 */
    private Consumer<Throwable> onError;

    /** 响应发射器处理类 */
    private ResponseEmitterHandler handler;

    /**
     * 设置超时时间(秒)
     * @param timeout 超时时间(秒)
     */
    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }

    @Override
    public long getTimeout() {
        return timeout;
    }

    @Override
    public void send(String data) {
        handler.send(data);
    }

    @Override
    public void send(byte[] data) {
        handler.send(data);
    }

    @Override
    public void completed() {
        handler.completed();
    }

    @Override
    public void onCompletion(Runnable runnable) {
        this.onCompletion = runnable;
    }

    @Override
    public void onError(Consumer<Throwable> consumer) {
        this.onError = consumer;
    }

    @Override
    public void onTimeout(Runnable runnable) {
        this.onTimeout = runnable;
    }

    /**
     * 获取超时回调函数
     * @return 超时回调函数
     */
    public Runnable getOnTimeout() {
        return onTimeout;
    }

    /**
     * 获取完成回调函数
     * @return 完成回调函数
     */
    public Runnable getOnCompletion() {
        return onCompletion;
    }

    /**
     * 获取错误回调函数
     * @return 错误回调函数
     */
    public Consumer<Throwable> getOnError() {
        return onError;
    }

    /**
     * 设置响应发射器处理类
     * @param handler 响应发射器处理类
     */
    public void setHandler(ResponseEmitterHandler handler) {
        this.handler = handler;
    }
}
